const chalk = require('chalk') // 命令行颜色
const { builtInRunPrefix, builtIn } = require('./config')

/**
 * 返回检测类型
 * @param {*} value - 要被检测类型的数据
 * @param {String} type - 匹配的类型 'String|Number|Boolean|Null|Undefined...'
 * @returns {String}
 */
const toType = (value, type) => {
  if (type) return Object.prototype.toString.call(value).slice(8, -1) === type
  return Object.prototype.toString.call(value).slice(8, -1)
}
exports.toType = toType

/**
 * 简化Promise流程
 * @param {[Promise, Array]} promise - 异步方法
 * @param {Object} cb - 回调方法 { before, after }
 */
const to = (method, cb) => {
  method = Array.isArray(method) ? method : [method]
  cb = toType(cb, 'Object') ? cb : {}
  cb.before && cb.before()
  return Promise.all(method)
    .then((res) => [null, ...res])
    .catch((err) => [err])
    .finally(() => {
      cb.after && cb.after()
    })
}
exports.to = to

// log
exports.defaultLog = (log) => console.log(chalk.blue(`---------------- ${log} ----------------`))
exports.errorLog = (log) => console.log(chalk.red(`---------------- ${log} ----------------`))
exports.successLog = (log) => console.log(chalk.green(`---------------- ${log} ----------------`))
exports.timeLog = (log) => console.time(chalk.white(`>>>>>${log}<<<<<`))
exports.timeEndLog = (log) => console.timeEnd(chalk.white(`>>>>>${log}<<<<<`))

/**
 * 生成指令函数
 * @param {String} script 指令
 */
exports.geoBuiltIn = (self, script, label) => {
  if (!script) return
  if (script.indexOf(builtInRunPrefix) === 0) { // 模式4 使用内置指令
    const model = Number(script.slice(builtInRunPrefix.length))
    if (Number.isNaN(model) || !builtIn[model]) return
    const cur = builtIn[model]
    return { fn: self[cur.run], label: cur.label }
  } else {
    if (self[script]) { // 选择模式3
      return { fn: self[script], label }
    }

    // 模式4
    return { fn: () => self._runCommand(script), label: label || script }
  }
}